#include <bits/stdc++.h>

#define eb emplace_back
#define ep emplace
#define fi first
#define se second
#define in read<int>()
#define lin read<ll>()
#define rep(i, x, y) for(int i = (x); i <= (y); i++)
#define per(i, x, y) for(int i = (x); i >= (y); i--)

using namespace std;

using ll = long long;
using db = double;
using pii = pair < int, int >;
using vec = vector < int >;
using veg = vector < pii >;

template < typename T > T read() {
	T x = 0; bool f = 0; char ch = getchar();
	while(!isdigit(ch)) f |= ch == '-', ch = getchar();
	while(isdigit(ch)) x = x * 10 + (ch ^ 48), ch = getchar();
	return f ? -x : x;
}

template < typename T > void chkmax(T &x, const T &y) { x = x > y ? x : y; }
template < typename T > void chkmin(T &x, const T &y) { x = x < y ? x : y; }

const int N = 1e6 + 10;

/* prime, mu, phi */
int mu[N], phi[N], pnum, pri[N];
bool v[N];

void shai(int l) {
	mu[1] = phi[1] = 1;
	rep(i, 2, l) {
		if(!v[i]) pri[++pnum] = i, mu[i] = -1, phi[i] = i - 1;
		rep(j, 1, pnum) {
			int t = i * pri[j]; if(t > l) break; v[t] = 1; 
			if(i % pri[j] == 0) { mu[t] = 0, phi[t] = phi[i] * pri[j]; break; }
			phi[t] = phi[i] * phi[pri[j]], mu[t] = -mu[i];
		}
	} 
}

vector < ll > factor(ll x) {
	vector < ll > pot;
	rep(i, 1, pnum) if(x % pri[i] == 0) pot.eb(pri[i]);
	return pot;
}

int main() {
#ifdef YJR_2333_TEST
	freopen("1.in", "r", stdin);
#endif
	shai(1000000);
	ll A = lin, B = lin, C = __gcd(A, B), ans = 0;
	while(A > 0 && B > 0) {
		if(A == B) { ans += 1; A = B = 0; break; }
		C = __gcd(A, B);
		if(C == 1) {
			ll t = abs(A - B);
			auto v = factor(t);
			auto get = [&](ll x, vector < ll > pot) {
				ll ret = x;
				for(auto v : pot) chkmin(ret, x % v);
				return ret;
			};
			ll l = min(A % t, get(A, v));
			if(l == 0) {
				ans += min(A, B) - 1;
				A = 1, B = 0;
			}
			//cerr << v << " " << l << endl;
			else A -= l, B -= l, ans += l - 1;
		} else A /= C, B /= C, A--, B--;
		ans++;// cerr << A << " " << B << endl;
	} cout << ans << endl;
	return 0;
}
